package com.youchu.pattern.design.behavioral.chain.spring;

import com.youchu.pattern.design.behavioral.chain.entity.User;
import com.youchu.pattern.design.behavioral.chain.handler.AbstractRegisterHandler;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Iterator;
import java.util.List;

/**
 * 用户注册责任链管理器
 */
@Component
public class RegisterHandlerManager {


    private final List<AbstractRegisterHandler> registerHandlers;

    @Autowired
    public RegisterHandlerManager(List<AbstractRegisterHandler> registerHandlers) {
        this.registerHandlers = registerHandlers;

        // 迭代集合，并为除第一个之外的每个节点设置下一个节点
        for (int i = 0; i < registerHandlers.size(); i++) {
            if (i < registerHandlers.size() - 1) {
                registerHandlers.get(i).setNext(registerHandlers.get(i + 1));
            }
        }
        registerHandlers.get(registerHandlers.size() - 1).setNext(new AbstractRegisterHandler() {
            @Override
            public void handleRequest(User user) {

            }
        });
    }

    public void handler(User user) {
        this.registerHandlers.get(0).handleRequest(user);
    }

}
